<?php

namespace app\api\service;

use app\common\exception\BusinessException;
use app\common\model\Category as CategoryModel;
use think\exception\ValidateException;

/**
 * 菜品服务
 */
class Dish
{
    /**
     * 条件查询菜品和口味
     *
     * @param array $data
     */
    public function listWithFlavor($data)
    {
        $result = [];
        // 根据分类id获取菜品
        $category = CategoryModel::get($data['categoryId']);
        if (!$category) {
            // 抛出业务异常
            throw new BusinessException("没有找到对应分类");
        }
        $result = [];
        // 获取售卖状态的菜品
        $dishes = $category->apiDishes()->select();
        if (empty($dishes)) {
            throw new BusinessException("分类下菜品为空");
        }
        foreach ($dishes as $key => $dish) {
            // 获取菜品口味
            $flavors = [];
            if ($dish->flavors) {
                foreach ($dish->flavors as $k => $flavor) {
                    $flavors[] = [
                        'dishId' => $flavor->dish_id,
                        'id' => $flavor->id,
                        'name' => $flavor->name,
                        'value' => $flavor->value,
                    ];
                }
            }
            // 构建返回数据
            $result[] = [
                'categoryId' => $category->id,
                'categoryName' => $category->name,
                'description' => $dish->description,
                'flavors' => $flavors,
                'id' => $dish->id,
                'image' => $dish->image,
                'name' => $dish->name,
                'price' => $dish->price,
            ];
        }
        return $result;
    }
}
